<template>
  <el-dialog
    ref="wkDialog"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :title="title"
    width="800px"
    @close="handleCancel">
    <div class="form-add-dialog-body">
      <el-form
        ref="formAddForm"
        :model="editForm"
        :rules="rules"
        :validate-on-rule-change="false"
        class="wk-form"
        inline
        style="overflow: hidden"
        label-position="top"
        @change="wkFormChange">
        <wk-form-item
          v-for="(item, index) in fields"
          :key="index"
          :index="index"
          :field-from="editForm"
          :item="item"
          :disabled="item.disabled"
          :style-percent="item.percent ? item.percent : '50%'"
        >
          <template slot-scope="scope">
            <wang-editor v-if="scope.data && scope.data.formType == 'editor' && showEditor" :editor-config="editorConfig" :default-content="editForm.reportContent || editForm.content || []" @change="editorChange" />
            <div v-if="scope.data && scope.data.formType == 'employee'" class="control-item">
              <span
                v-for="(item, index) in showOwnerUserList"
                :key="index"
                class="send-user">
                <el-tooltip
                  placement="bottom"
                  effect="light"
                  popper-class="tooltip-change-border">
                  <div slot="content">
                    <span>{{ item.realname || item.name }}</span>
                  </div>
                  <xr-avatar
                    :name="item.realname || item.name"
                    :size="32"
                    :src="item.img" />
                </el-tooltip>
              </span>
              <members-dep
                :content-block="false"
                :user-checked-data="editForm.ownerUserList || []"
                :close-dep="true"
                @popoverSubmit="sendUserChange">
                <span slot="membersDep" style="position: relative; bottom: 12px;">
                  <el-tooltip
                    placement="bottom"
                    effect="light"
                    popper-class="tooltip-change-border">
                    <div slot="content">
                      <span>{{ sendUserNames }}</span>
                    </div>
                    <i
                      v-show="(editForm.ownerUserList ? editForm.ownerUserList.length : 0) > 5"
                      class="el-icon-more more-user-btn" />
                  </el-tooltip>

                  <el-button type="info" size="default" icon="el-icon-plus" circle />
                </span>
              </members-dep>
            </div>
            <div v-if="scope.data && scope.data.formType == 'image'" class="img-box">
              <el-upload
                ref="imageUpload"
                :action="crmFileSaveUrl"
                :headers="httpHeader"
                :on-success="imgFileUploadSuccess"
                :multiple="false"
                :limit="1"
                :show-file-list="false"
                class="img-uploader"
                name="file"
                accept="image/*">
                <p v-if="!editForm.liveData" class="add-img">
                  <span class="el-icon-picture" />
                  <span>添加图片</span>
                </p>
                <el-image v-else :src="baseApi + '/adminFile/down/' + editForm.liveData" style="width: 100px; height: 100px" />
              </el-upload>
            </div>
          </template>
        </wk-form-item>
      </el-form>
      <slot />
    </div>
    <span
      slot="footer"
      class="dialog-footer">
      <el-button @click.native="handleCancel">取消</el-button>
      <el-button
        v-debounce="handleConfirm"
        type="primary">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import WkForm from '@/components/NewCom/WkForm'
import { crmFileSaveUrl } from '@/api/common'

import { objDeepCopy } from '@/utils'
import ElDialogLoadingMixin from '@/mixins/ElDialogLoading'
import WangEditor from '@/components/Editor'
import MembersDep from '@/components/SelectEmployee/MembersDep'
import WkFormItem from '@/components/NewCom/WkForm/WkFormItem'
import axios from 'axios'

export default {

  // 组织操作
  name: 'FormAddDialog',
  components: {
    WkForm,
    WangEditor,
    MembersDep,
    WkFormItem
  },
  mixins: [ElDialogLoadingMixin],
  props: {
    title: String,
    form: Object,
    rules: Object,
    fields: Array,
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      editForm: {},
      editorConfig: {
        placeholder: '请输入...',
        autoFocus: true,
        MENU_CONF: {}
      },
      showEditor: false,
      // 直播图片上传路径
      crmFileSaveUrl: crmFileSaveUrl
    }
  },
  computed: {
    sendUserNames() {
      const sendUserName = this.editForm.ownerUserList && this.editForm.ownerUserList.length > 0 ? `${this.editForm.ownerUserList.length}个员工` : ''
      const names = []
      if (sendUserName) {
        names.push(sendUserName)
      }
      return `等${names.join('和')}`
    },
    showOwnerUserList() {
      const ownerUserList = this.editForm.ownerUserList || []
      return ownerUserList.slice(0, 5)
    },
    month() {
      return this.editForm.month
    },
    baseApi() {
      return process.env.BASE_API
    },
    httpHeader() {
      return {
        'Admin-Token': axios.defaults.headers['Admin-Token']
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            if (this.$refs.formAddForm) {
              this.editForm = objDeepCopy(this.form || {})
              if (this.editForm.reportContent) {
                this.editForm.reportContent = JSON.parse(this.editForm.reportContent)
              }
              if (this.editForm.content) {
                this.editForm.content = JSON.parse(this.editForm.content)
              }
              this.showEditor = true
              this.$refs.formAddForm.clearValidate()
            }
          })
        }
      },
      immediate: true
    },
    form: {
      handler(val) {
        this.editForm = objDeepCopy(this.form || {})
      },
      immediate: true
    },
    editForm: {
      handler() {
        if (this.editForm.actual != undefined && this.editForm.complete != undefined) {
          this.$set(this.editForm, 'completeNow', Number(this.editForm.actual) + Number(this.editForm.complete))
          this.$set(this.editForm, 'completeProgress', Math.floor(this.editForm.completeNow / this.editForm.target * 100))
        }
        if (this.editForm.target && this.editForm.actual) {
          this.$set(this.editForm, 'completedWeek', Math.floor(Number(this.editForm.actual) * 100 / Number(this.editForm.target)))
        }
      },
      deep: true
    },
    month(val) {
      if (val && val.indexOf('-') != -1) {
        this.editForm.targetYear = Number(val.split('-')[0])
        this.editForm.targetMonth = Number(val.split('-')[1])
      }
    }
  },
  mounted() {},
  methods: {

    editorChange(editor) {
      this.editForm.reportContent = editor.children
      this.editForm.content = editor.children
      // 获取html
      // editor.getHtml()
    },
    /**
     * 取消选择
     */
    handleCancel() {
      this.$emit('update:visible', false)
      this.showEditor = false
    },

    /**
     * 点击确定
     */
    handleConfirm() {
      this.$refs.formAddForm.validate(valid => {
        if (valid) {
          this.$emit('update:form', this.editForm)
          this.$emit('pass')
        }
      })
    },

    /**
     * change 事件
     */
    wkFormChange(item, index, value, valueList) {
      this.$emit('change', item, index, value, valueList, this.editForm)
    },

    /**
     * 发送人选择
     */
    sendUserChange(users) {
      this.editForm.ownerUserList = users
      this.editForm.ownerUserIds = users.map(item => item.userId).join(',')
    },
    // 上传图片成功
    imgFileUploadSuccess(response, file, fileList) {
      this.$set(this.editForm, 'liveData', response.data.fileId)
    }
  }
}
</script>
<style lang="scss" scoped>
.form-add-dialog-body {
  overflow-y: auto;
  overflow-x: hidden;
  max-height: 55vh;
}
// 参与人
.send-user {
  position: relative;
  display: inline-block;
  cursor: pointer;
}
.send-user + .send-user {
  margin-left: 7px;
}
.more-user-btn {
  background-color: #F3F7FF;
  border-radius: 50%;
  padding: 5px;
  font-size: 12px;
  color: #666;
  margin-left: 7px;
  &:hover {
    background-color: $xr-color-primary;
    color: white;
  }
}

.img-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.img-uploader /deep/ .el-upload:hover {
  border-color: #409EFF;
}
.add-img {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
</style>
